/* 
 * Copyright [2018] [Alex/libo(liboware@gmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.codex.redis.service.impl;

import java.util.Objects;
import java.util.stream.Stream;

import com.hyts.codex.redis.model.JedisConnection;
import com.hyts.codex.redis.service.IMsgApi;

import lombok.AllArgsConstructor;
import lombok.Data;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

/** 
 * @author LiBo/Alex
 * @version V1.0 
 */
@Data
@AllArgsConstructor
public abstract class RMsgService implements IMsgApi<String> {
    
    /**
     * connection subject
     */
    private JedisConnection connection;
    
    private Integer dbIndex;
    
    
    
    /* (非 Javadoc)
     * @param param
     * @param channels
     * @return
     * @see com.hyts.ssm.api.IMsgApi#send(java.lang.Object, java.lang.String[])  
     * @exception
     */ 
    @Override
    public boolean send(String param, String... channels) {
        Jedis session = connection.openSession().orElse(connection.openSession().get());
        session.select(dbIndex);
        try {
            Stream.of(channels).forEach(channel -> {
                session.publish(channel, param);
            });
        } finally {
            if(!Objects.isNull(session)) {
                session.close();
            }
        }
        return true;
    }
    
    

    @Override
    public boolean startConsume(String... channels) {
        Jedis session = connection.openSession().orElse(connection.openSession().get());
        session.select(dbIndex);
        session.subscribe(new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                consume(message);
            }
        }, channels);
        return false;
    }

    /* (非 Javadoc)
     * @param param
     * @param channels
     * @see com.hyts.ssm.api.IMsgApi#consume(java.lang.Object, java.lang.String[])  
     * @exception
     */ 
    public abstract void consume(String param);



    public RMsgService(JedisConnection connection) {
        super();
        this.connection = connection;
        this.dbIndex = 0;
    }
}
